// cursor_extension.js - VS Code扩展示例
const vscode = require('vscode');
const axios = require('axios');
const fs = require('fs');
const path = require('path');

// MCP服务器URL
const MCP_SERVER_URL = 'http://localhost:8080/run';

/**
 * 激活扩展
 * @param {vscode.ExtensionContext} context
 */
function activate(context) {
    console.log('MCP扩展已激活');

    // 注册命令：运行当前文件中的Python代码
    let runCurrentFileCommand = vscode.commands.registerCommand('mcp.runCurrentFile', async function () {
        try {
            // 获取当前编辑器
            const editor = vscode.window.activeTextEditor;
            if (!editor) {
                vscode.window.showErrorMessage('没有打开的编辑器');
                return;
            }

            // 获取当前文件内容
            const document = editor.document;
            const code = document.getText();

            // 打开输入框让用户输入依赖
            const dependenciesInput = await vscode.window.showInputBox({
                prompt: '输入依赖包（用逗号分隔）',
                placeHolder: '例如: numpy,matplotlib'
            });

            // 解析依赖
            const dependencies = dependenciesInput
                ? dependenciesInput.split(',').map(dep => dep.trim()).filter(dep => dep)
                : [];

            // 创建输出通道
            const outputChannel = vscode.window.createOutputChannel('MCP执行结果');
            outputChannel.show();

            // 显示状态消息
            vscode.window.withProgress({
                location: vscode.ProgressLocation.Notification,
                title: "MCP代码执行中",
                cancellable: false
            }, async (progress) => {
                // 发送代码到MCP服务器
                const result = await sendCodeToMCP(code, dependencies);

                // 显示结果
                outputChannel.appendLine('=== 执行结果 ===');
                
                if (result.error) {
                    outputChannel.appendLine(`错误: ${result.error}`);
                    if (result.details) {
                        outputChannel.appendLine(`详情: ${result.details}`);
                    }
                } else {
                    outputChannel.appendLine('标准输出:');
                    outputChannel.appendLine(result.stdout || '');
                    
                    if (result.stderr) {
                        outputChannel.appendLine('\n标准错误:');
                        outputChannel.appendLine(result.stderr);
                    }
                    
                    // 处理返回的文件
                    if (result.files && result.files.length > 0) {
                        const savedFiles = await saveOutputFiles(result.files);
                        if (savedFiles.length > 0) {
                            outputChannel.appendLine(`\n生成的文件已保存: ${savedFiles.join(', ')}`);
                            
                            // 显示第一个图片文件（如果是图片）
                            const imageFile = savedFiles.find(file => 
                                ['.png', '.jpg', '.jpeg', '.gif', '.svg'].includes(path.extname(file).toLowerCase())
                            );
                            
                            if (imageFile) {
                                vscode.commands.executeCommand('vscode.open', vscode.Uri.file(imageFile));
                            }
                        }
                    }
                }
                
                return Promise.resolve();
            });
        } catch (error) {
            vscode.window.showErrorMessage(`执行失败: ${error.message}`);
        }
    });

    // 注册命令：运行选中的Python代码
    let runSelectedCodeCommand = vscode.commands.registerCommand('mcp.runSelectedCode', async function () {
        try {
            // 获取当前编辑器
            const editor = vscode.window.activeTextEditor;
            if (!editor) {
                vscode.window.showErrorMessage('没有打开的编辑器');
                return;
            }

            // 获取选中的代码
            const selection = editor.selection;
            if (selection.isEmpty) {
                vscode.window.showErrorMessage('没有选中代码');
                return;
            }
            const selectedCode = editor.document.getText(selection);

            // 打开输入框让用户输入依赖
            const dependenciesInput = await vscode.window.showInputBox({
                prompt: '输入依赖包（用逗号分隔）',
                placeHolder: '例如: numpy,matplotlib'
            });

            // 解析依赖
            const dependencies = dependenciesInput
                ? dependenciesInput.split(',').map(dep => dep.trim()).filter(dep => dep)
                : [];

            // 创建输出通道
            const outputChannel = vscode.window.createOutputChannel('MCP执行结果');
            outputChannel.show();

            // 显示状态消息
            vscode.window.withProgress({
                location: vscode.ProgressLocation.Notification,
                title: "MCP代码执行中",
                cancellable: false
            }, async (progress) => {
                // 发送代码到MCP服务器
                const result = await sendCodeToMCP(selectedCode, dependencies);

                // 显示结果
                outputChannel.appendLine('=== 执行结果 ===');
                
                if (result.error) {
                    outputChannel.appendLine(`错误: ${result.error}`);
                    if (result.details) {
                        outputChannel.appendLine(`详情: ${result.details}`);
                    }
                } else {
                    outputChannel.appendLine('标准输出:');
                    outputChannel.appendLine(result.stdout || '');
                    
                    if (result.stderr) {
                        outputChannel.appendLine('\n标准错误:');
                        outputChannel.appendLine(result.stderr);
                    }
                    
                    // 处理返回的文件
                    if (result.files && result.files.length > 0) {
                        const savedFiles = await saveOutputFiles(result.files);
                        if (savedFiles.length > 0) {
                            outputChannel.appendLine(`\n生成的文件已保存: ${savedFiles.join(', ')}`);
                        }
                    }
                }
                
                return Promise.resolve();
            });
        } catch (error) {
            vscode.window.showErrorMessage(`执行失败: ${error.message}`);
        }
    });

    context.subscriptions.push(runCurrentFileCommand);
    context.subscriptions.push(runSelectedCodeCommand);
}

/**
 * 发送代码到MCP服务器
 * @param {string} code 要执行的Python代码
 * @param {Array<string>} dependencies 依赖包列表
 * @returns {Promise<Object>} 执行结果
 */
async function sendCodeToMCP(code, dependencies) {
    try {
        const response = await axios.post(MCP_SERVER_URL, {
            code: code,
            dependencies: dependencies
        });
        
        return response.data;
    } catch (error) {
        if (error.response) {
            return {
                error: `请求失败: ${error.response.status}`,
                details: JSON.stringify(error.response.data)
            };
        } else {
            return {
                error: `请求失败: ${error.message}`
            };
        }
    }
}

/**
 * 保存MCP服务器返回的文件
 * @param {Array<Object>} files 文件数组
 * @returns {Promise<Array<string>>} 保存的文件路径数组
 */
async function saveOutputFiles(files) {
    const savedFiles = [];
    
    // 创建输出目录
    const workspaceFolder = vscode.workspace.workspaceFolders[0];
    if (!workspaceFolder) {
        return savedFiles;
    }
    
    const outputDir = path.join(workspaceFolder.uri.fsPath, 'mcp_output');
    if (!fs.existsSync(outputDir)) {
        fs.mkdirSync(outputDir, { recursive: true });
    }
    
    // 保存每个文件
    for (const file of files) {
        const fileName = file.name;
        const content = file.content;
        
        if (content) {
            const filePath = path.join(outputDir, fileName);
            const buffer = Buffer.from(content, 'base64');
            
            fs.writeFileSync(filePath, buffer);
            savedFiles.push(filePath);
        }
    }
    
    return savedFiles;
}

/**
 * 扩展被停用时调用
 */
function deactivate() {
    console.log('MCP扩展已停用');
}

module.exports = {
    activate,
    deactivate
}; 